<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户id" prop="uid">
        <el-input
          v-model="queryParams.uid"
          placeholder="请输入用户id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺id" prop="mid">
        <el-input
          v-model="queryParams.mid"
          placeholder="请输入店铺id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="救援状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择救援状态" @change="handleQuery" style="width: 200px;" clearable>
          <el-option
            v-for="dict in help_status"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['help:helptask:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['help:helptask:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['help:helptask:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['help:helptask:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="helptaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键编号" align="center" prop="id" /> -->
      <el-table-column label="用户" align="center" prop="uid" />
       
      <el-table-column label="店铺" align="center" prop="mid" >
        <template #default="scope">
          {{ getMerchantName(scope.row.mid)  }}
        </template>
      </el-table-column>
      <el-table-column label="发起时间" align="center" prop="time" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="救援类型" align="center" prop="typeId" >
        <template #default="scope">
          {{ getTypeName(scope.row.typeId)  }}
        </template>
        </el-table-column>
      <el-table-column label="当前位置" align="center" prop="position" />
      <el-table-column label="终点" align="center" prop="end" />
      <el-table-column label="求助人" align="center" prop="name" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="车号" align="center" prop="carNum" />
      <el-table-column label="车型" align="center" prop="carType">
        <template #default="scope">
          <dict-tag :options="car_type" :value="scope.row.carType"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="求助信息描述" align="center" prop="description" /> -->
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="help_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280"> <!-- 适当增加宽度 -->
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['help:helptask:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['help:helptask:remove']">删除</el-button>
          <!-- 新增接单按钮 -->
          <el-button v-if="scope.row.status === 0"link type="success" icon="Check" @click="handleAcceptOrder(scope.row)" v-hasPermi="['help:helptask:accept']">接单</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改救援订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="helptaskRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="uid">
          <el-input v-model="form.uid" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="店铺id" prop="mid">
          <el-input v-model="form.mid" placeholder="请输入店铺id" />
        </el-form-item>
        <el-form-item label="发起时间" prop="time">
          <el-date-picker clearable
            v-model="form.time"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择发起时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="救援类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择救援类型">
            <el-option v-for="type in helptypeList" :key="type.id" :label="type.name" :value="type.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前位置" prop="position">
          <el-input v-model="form.position" placeholder="请输入当前位置/起点" />
        </el-form-item>
        <el-form-item label="终点" prop="end">
          <el-input v-model="form.end" placeholder="请输入终点" />
        </el-form-item>
        <el-form-item label="求助人" prop="name">
          <el-input v-model="form.name" placeholder="请输入求助人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="车号" prop="carNum">
          <el-input v-model="form.carNum" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="车型" prop="carType">
          <el-select v-model="form.carType" placeholder="请选择车型">
            <el-option
              v-for="dict in car_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="求助信息描述">
          <editor v-model="form.description" :min-height="192"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in help_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Helptask">
import { listHelptask, getHelptask, delHelptask, addHelptask, updateHelptask } from "@/api/help/helptask"
import { listHelptype} from "@/api/help/helptype"
import { listMerchant} from "@/api/merchant/merchant"


const { proxy } = getCurrentInstance()
const { car_type, help_status } = proxy.useDict('car_type', 'help_status')

const helptaskList = ref([])
const helptypeList = ref([])
const merchantList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    uid: null,
    mid: null,
    typeId: null,
    status: null,
  },
  rules: {
    deleted: [
      { required: true, message: "删除状态不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询救援订单列表 */
function getList() {
  loading.value = true
  listHelptask(queryParams.value).then(response => {
    helptaskList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
/** 查询救援类型列表 */
function getList2() {
  loading.value = true
  listHelptype().then(response => {
    helptypeList.value = response.rows
  })
}
/** 查询商户列表 */
function getList3() {
  loading.value = true
  listMerchant().then(response => {
    merchantList.value = response.rows
  })
}
//根据救援类型id获取救援类型名称
function getTypeName(typeId) {
  const typeItem = helptypeList.value.find(type => type.id === typeId);
  return typeItem ? typeItem.name : '';
}
//根据商户id获取商户名称
// 根据商户id获取商户名称
function getMerchantName(merchantId) {
  const merchantItem = merchantList.value.find(merchant => merchant.id === merchantId);
  return merchantItem ? merchantItem.name : '';
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    uid: null,
    mid: null,
    time: null,
    typeId: null,
    position: null,
    end: null,
    name: null,
    phone: null,
    carNum: null,
    carType: null,
    description: null,
    status: null,
    deleted: null
  }
  proxy.resetForm("helptaskRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加救援订单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getHelptask(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改救援订单"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["helptaskRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateHelptask(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addHelptask(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除救援订单编号为"' + _ids + '"的数据项？').then(function() {
    return delHelptask(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('help/helptask/export', {
    ...queryParams.value
  }, `helptask_${new Date().getTime()}.xlsx`)
}

/** 接单按钮操作 */
function handleAcceptOrder(row) {
  
  const newStatus = 1; 
  const updatedForm = { ...row, status: newStatus };

  proxy.$modal.confirm('是否确认接收该救援订单？').then(() => {
    updateHelptask(updatedForm).then(response => {
      proxy.$modal.msgSuccess("接单成功");
      getList(); // 刷新列表
    }).catch(error => {
      proxy.$modal.msgError("接单失败，请稍后重试");
      console.error('接单失败:', error);
    });
  }).catch(() => {});
}

getList()
getList2()
getList3()
</script>
